﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;

namespace iRingtones
{
    public partial class frmMain : Form
    {
        //Custom class storing the locations of the nero aac encorder and the users iTunes library
        private Locations locations;

        public frmMain()
        {
            locations = new Locations();

            InitializeComponent();
        }

        private void frmMain_Load(object sender, EventArgs e)
        {
            //Check for startup file
            if (System.IO.File.Exists(Application.StartupPath + "\\data.xml"))
            {
                locations = locations.Load(Application.StartupPath + "\\data.xml");
                txtiTunes.Text = locations.iTunesLibrary;
                txtNero.Text = locations.NeroAacEnc;
            }
        }

        private void btnNero_Click(object sender, EventArgs e)
        {
            openFileDialog1.CheckFileExists = true;
            openFileDialog1.CheckPathExists = true;
            openFileDialog1.DefaultExt = ".exe";
            openFileDialog1.Filter = "NeroAacEnc|neroAacEnc.exe";
            openFileDialog1.Title = "Nero AAC Encoder";
            openFileDialog1.FileName = "neroAacEnc.exe";
            openFileDialog1.ShowDialog();

            if (System.IO.File.Exists(openFileDialog1.FileName))
                txtNero.Text = openFileDialog1.FileName;

            locations.NeroAacEnc = txtNero.Text;
            locations.Save(Application.StartupPath + "\\data.xml");
        }

        private void btniTunes_Click(object sender, EventArgs e)
        {
            folderBrowserDialog1.Description = "Select the location of your 'iTunes Music' folder";
            folderBrowserDialog1.ShowDialog();

            if (System.IO.Directory.Exists(folderBrowserDialog1.SelectedPath))
            {
                bool failed = folderBrowserDialog1.SelectedPath.EndsWith("Ringtones");

                //perform a quick check to make sure we are not within the ringtones folder
                if (failed)
                {
                    MessageBox.Show("You have selected the iTunes ringtones folder and this is an invalid folder. Please select ONLY your iTunes Music library folder containing all of your music.\n\nThe software will automatically place the ringtone in the correct Ringtones folder.");
                    txtiTunes.Clear();
                    return; 
                }


                txtiTunes.Text = folderBrowserDialog1.SelectedPath;
            }
            locations.iTunesLibrary = txtiTunes.Text;
            locations.Save(Application.StartupPath + "\\data.xml");
        }

        private void btnConvert_Click(object sender, EventArgs e)
        {
            openFileDialog1.CheckFileExists = true;
            openFileDialog1.CheckPathExists = true;
            openFileDialog1.DefaultExt = ".wav";
            openFileDialog1.Filter = "Wave Files (*.wav)|*.wav";
            openFileDialog1.FileName = "";

            //Save the locations incase they where manually changed.
            locations.Save(Application.StartupPath + "\\data.xml");

            if (txtiTunes.Text == "")
            {
                MessageBox.Show("Please set all of your paths before attempting to generate a ring tone.");
                return;
            }

            if (txtNero.Text == "")
            {
                MessageBox.Show("Please set all of your paths before attempting to generate a ring tone.");
                return;
            }

            //make sure the files still exist
            if (!System.IO.File.Exists(locations.NeroAacEnc))
            {
                MessageBox.Show("Failed to locate the Nero AAC Encoder.\nPlease re-set the location of the encoder.");
                return; 
            }

            if (!System.IO.Directory.Exists(locations.iTunesLibrary))
            {
                MessageBox.Show("Failed to locate the iTunes Music Library.\nPlease re-select where the library is located at.");
                return;
            }
            openFileDialog1.ShowDialog();

            //perform checks and balances
            if (string.IsNullOrEmpty(openFileDialog1.FileName))
            {
                MessageBox.Show("Ringtone convert canceled.");
                return; 
            }
            if (!System.IO.File.Exists(openFileDialog1.FileName))
            {
                MessageBox.Show("Selected ringtone file does not exist.\nConversion halted.");
                return;
            }

            if (!System.IO.Directory.Exists(locations.iTunesLibrary + "\\Ringtones"))
                System.IO.Directory.CreateDirectory(locations.iTunesLibrary + "\\Ringtones");

            System.Diagnostics.Process process = new System.Diagnostics.Process();
            System.Diagnostics.ProcessStartInfo info = new System.Diagnostics.ProcessStartInfo();

            string inputFile = openFileDialog1.FileName;
            string filename = System.IO.Path.GetFileName(inputFile);
            string correctFilename = filename.Substring(0, filename.Length - System.IO.Path.GetExtension(filename).Length);
            string ringtoneFilename = correctFilename + ".m4r";

            if (System.IO.File.Exists(locations.iTunesLibrary + "\\Ringtones\\" + ringtoneFilename))
            {
                DialogResult result = MessageBox.Show("The ringtone '" + ringtoneFilename + "' already exists, would you like to overwrite it?", "Existing Ringtone", MessageBoxButtons.YesNo);

                if (result == DialogResult.No)
                    return;
            }

            //neroAacEnc first
            info.Arguments = " -if \"" + inputFile + "\" -of \"" + locations.iTunesLibrary + "\\Ringtones\\" + ringtoneFilename + "\"";
            info.FileName = locations.NeroAacEnc;
            info.UseShellExecute = true;
            info.WorkingDirectory = locations.NeroAacEnc;
            info.CreateNoWindow = false;

            process.StartInfo = info;
            process.Start();
            process.WaitForExit();

            //reset the process for adding into itunes
            info = new System.Diagnostics.ProcessStartInfo(locations.iTunesLibrary + "\\Ringtones\\" + ringtoneFilename);
            info.WorkingDirectory = locations.iTunesLibrary + "\\Ringtones";
            process.StartInfo = info;
            process.Start();
            MessageBox.Show("Ringtone created and added to the iTunes library!");
            Application.Exit();
        }

        private void txtNero_TextChanged(object sender, EventArgs e)
        {
            locations.NeroAacEnc = txtNero.Text;
        }

        private void txtiTunes_TextChanged(object sender, EventArgs e)
        {
            locations.iTunesLibrary = txtiTunes.Text;
        }
    }
}
